<?php
/**
 * Description: 推广公开课的链接,无用户校验
 * User: devforma
 * Date: 16/3/29
 * Time: 20:17
 */
require LIB_DIR . '/LiveCourse.class.php';
class PromoteCourseUrl implements iController {

    /**
     * api请求处理主函数
     * @param array $queryArgs 就是$_REQUEST变量
     * @return array api返回结果，必须含response_code
     */
    public function output($queryArgs) {

        if (empty($queryArgs['course_id']) || !filter_var($queryArgs['course_id'], FILTER_VALIDATE_INT)) {
            return genOutput(1000);
        }

        $now = time();

        //获取公开课课程信息
        $openClass = LiveCourse::getOpenClassInfo($queryArgs['course_id']);

        //无此公开课或已经过了7天则不允许再看
        if (!$openClass || strtotime($openClass->start_time) < $now - 7*24*60*60) {
            return genOutput(1000);
        }

        //推广来源标记
        $utmSource = empty($queryArgs['utm_source']) ? '' : $queryArgs['utm_source'];

        if ($openClass->live_platform === '多贝云') {
            return genOutput(1, array(
                'url' => "http://weixin.duobeiyun.com/state/{$openClass->room_id}?utm_source={$utmSource}"
            ));

        } elseif ($openClass->live_platform === '欢拓云') {
            $guestId = self::generateHtGuestId();
            $isPlayback = strtotime($openClass->end_time) < $now;

            return genOutput(1, array(
                'url' => LiveCourse::GetHtClassUrl($openClass->id, $openClass->maituo_room_id, $guestId, $guestId, $isPlayback, 'guest')
            ));

        } else {
            return genOutput(1000);
        }
    }

    /**
     * 创建欢拓游客随机id
     *
     * @return string
     */
    private static function generateHtGuestId() {
        if (function_exists('com_create_guid')) {
            return com_create_guid();
        } else {
            $charid = strtoupper(md5(uniqid(rand(), true)));
            $hyphen = chr(45);
            $uuid = substr($charid, 0, 8) . $hyphen
                . substr($charid, 8, 4) . $hyphen
                . substr($charid, 12, 4) . $hyphen
                . substr($charid, 16, 4) . $hyphen
                . substr($charid, 20, 12);
            return $uuid;
        }
    }
}